<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/30
 * Time: 16:49
 */
require 'vendor/autoload.php';
require 'connect.php';
use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use Slim\PDO\Database;
use Slim\PDO\Statement;
use Slim\PDO\Statement\SelectStatement;
$app = new \Slim\App();

$app->post('/addContact',function(Request $request,Response $response){
    $response=$response->withAddedHeader('Access-Control-Allow-Origin','*');
    $response=$response->withAddedHeader('Content-Type','application/json');
    $database=localhost();
    $body = $request->getBody();
    $body=json_decode($body);
    $phone=$body->phone;//获取body中数据
    $contact=$body->contact;
    $array=array();
    foreach($body as $key=>$value){
        $array[$key]=$value;
    }
    if(preg_match('/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\\d{8}$/',$phone)){
        if($contact!=null||$contact!=""){
                    $selectStatement = $database->select()
                        ->from('contact')
                        ->where('phone','=',$phone);
                    $stmt = $selectStatement->execute();
                    $data = $stmt->fetch();
                    if(!$data){
                        $insertStatement = $database->insert(array_keys($array))
                            ->into('contact')
                            ->values(array_values($array));
                        $insertId = $insertStatement->execute(false);
                        return $response->withJson(array("result" => "0", "desc" => "success"));
                    }else{
                        return $response->withJson(array("result" => "1", "desc" => "电话号码已注册"));
                    }
        }else{
            return $response->withJson(array("result"=>"2","desc"=>"缺少姓名"));
        }
    }else{
        return $response->withJson(array("result"=>"3","desc"=>"电话格式不正确"));
    }
});


$app->run();

function localhost()
{
    return connect();
}


?>